<?php
namespace dwc_app;

session_start();
ob_start();
include_once('config.php');

$file_upload = null;
if(@$_FILES['file_upload']) $file_upload = $_FILES['file_upload'];
$file_url = @$_REQUEST['file_url'];
$table_type = @$_REQUEST['table_type'];
$uri = null;


echo '<link href="style.css" media="screen" rel="stylesheet" type="text/css" />';

if($file_url)
{
    if(!preg_match("/^(.*)\.(tgz|tar\.gz|tar\.gzip)$/", $file_upload['name'], $arr)) throw new Exception("DarwinCore Archive must be tar/gzip");
    $uri = $file_url;
}elseif(@$file_upload['tmp_name'])
{
    if(!preg_match("/^(.*)\.(tgz|tar\.gz|tar\.gzip)$/", $file_upload['name'], $arr)) throw new Exception("DarwinCore Archive must be tar/gzip");
    shell_exec("mv ".$file_upload['tmp_name']." ".DOC_ROOT."/tmp/test.tar.gz");
    $uri = DOC_ROOT."/tmp/test.tar.gz";
}

if($uri)
{
    echo "<h3>Loading...</h3>";
    echo "Powered by Google<br>";
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
    $dwca = new DarwinCoreArchiveReader($uri);
    if($table_type == 'fusion_tables')
    {
        $dwc_uploader = new FusionArchiveUploader($dwca, $GLOBALS['GOOGLE_USERNAME'], $GLOBALS['GOOGLE_PASSWORD']);
        $dwc_uploader->send_core_to_fusion_tables();
        
        $dwc_uploader = new SpreadsheetsArchiveUploader($dwca, $GLOBALS['GOOGLE_USERNAME'], $GLOBALS['GOOGLE_PASSWORD']);
        $dwc_uploader->send_core_to_spreadsheets();
    }else
    {
        $dwc_uploader = new SpreadsheetsArchiveUploader($dwca, $GLOBALS['GOOGLE_USERNAME'], $GLOBALS['GOOGLE_PASSWORD']);
        $dwc_uploader->send_core_to_spreadsheets();
        
    }
}else
{
    echo "<h3>Choose a DwC-A to send to Google Fusion Tables / Spreadsheets</h3>
        <span class='powered'>Powered by Google</span><br><br><br><br>
        <form name='validator_form' action='upload.php' method='post' enctype='multipart/form-data'>
            <table align='center'>
                <tr>
                    <td>File URL:</td>
                    <td><input type='text' size='30' name='file_url'";
            if($file_url) echo " value='$file_url'";
            echo "/></td>
                </tr>
                <tr>
                    <td>File Upload:</td>
                    <td><input type='file' name='file_upload' id='file_upload'/></td>
                </tr>
                <tr>
                    <td>Create as:</td>
                    <td><select name='table_type' style='width: 400px'>
                    <option value='fusion_tables'>Google Fusion Table
                    <option value='spreadsheets'>Google Spreadsheet
                    </select></td>
                </tr>
                <tr>
                    <td colspan='2' align='center'>
                        <br/>
                        <input type='submit' value='Submit'>
                    </td>
                </tr>
            </table>
        </form>";
}

?>